package com.shmilyou.dissertationmanagement.interceptor;
/* Created with 岂止是一丝涟漪     530060499@qq.com    2018/11/23 */

import com.shmilyou.dissertationmanagement.resolver.LoginUser;
import com.shmilyou.dissertationmanagement.utils.ConfigUtils;
import com.shmilyou.dissertationmanagement.utils.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginInterceptor implements HandlerInterceptor {

    private final static Logger log = LoggerFactory.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        Object loginUser = request.getSession().getAttribute(Constant.LOGIN_USER);
        if (loginUser == null) {
            if (ConfigUtils.getDebug()) {
                log.info("测试环境");
                request.getSession().setAttribute(Constant.LOGIN_USER, LoginUser.getInstance());
                return true;
            }

            //记录下当前访问的url，用于登录后跳转
            StringBuffer requestURI = request.getRequestURL();
            requestURI = request.getQueryString() != null ? requestURI.append("?").append(request.getQueryString()) : requestURI;
            request.getSession().setAttribute("requestURI", requestURI.toString());
            response.sendRedirect(request.getContextPath() + "/login");
            return false;
        }
        return true;
    }
}
